package com.linkage.jz.bankruptcy.activity.Project.ZQUser;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.CreateAddrActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.DetailOper.ApplyAddProxyUserActivity;
import com.linkage.jz.bankruptcy.bean.ApplyChangerZQUserNameBean;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailBaseInfo;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.ApplyBaseReplyDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.base.BaseWhiteCreateActivity;
import com.linkage.seapeak.utils.ToastUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ApplyChangeToMeActivity extends BaseWhiteCreateActivity {


    private static ApplyChangerZQUserNameBean mInfo;
    private String creditorId;

    private int REQUEST_CODE_ADDRESS = 10001;
    PublicNoticeDialog noticeDialog;

    private TextView creditorName;
    private TextView tv_zq_phone;
    private TextView tv_zq_other_phone;
    private TextView tv_zq_id;
    private TextView sendAddress;
    private TextView edit_detail, tv_zq_email;
    private TextView btn_commit;
    private static int mType; //0审核，1查看

    private ApplyBaseReplyDialog dialog;


    protected ShapeLoadingDialog mShapeLoadingDialog;


    public static void start(Context context, ApplyChangerZQUserNameBean info, int type) {
        Intent intent = new Intent(context, ApplyChangeToMeActivity.class);
//        intent.putExtra("mInfo", mInfo);
        mInfo = info;
        mType = type;
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_change_tome, "变更为本人操作");
        mShapeLoadingDialog = new ShapeLoadingDialog(this);
        initView();
//        btn_commit.setText("提交");
        btn_commit = findViewById(R.id.btn_commit);
        if (mType == 0) {
            btn_commit.setVisibility(View.VISIBLE);
        } else {
            btn_commit.setVisibility(View.GONE);
        }

        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog = new ApplyBaseReplyDialog(ApplyChangeToMeActivity.this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.btn_save) {
                            String msg = dialog.text_reason.getText().toString().trim();
                            String status = "1";
                            if (dialog.cb_nopass.isChecked()) {
                                status = "2";
                            }
                            String notifyTypes = "";
                            if (dialog.send_msg.isChecked() && dialog.send_phone.isChecked()) {
                                notifyTypes = "0,1";
                            } else if (dialog.send_msg.isChecked()) {
                                notifyTypes = "0";
                            } else {
                                notifyTypes = "1";
                            }


//                    addZQUser(name,phone);
                            applyPerson(status, msg, notifyTypes);
                            dialog.dismiss();
                        }
                        if (v.getId() == R.id.btn_chancel) {
                            dialog.dismiss();
                        }

                    }
                });
                dialog.show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_ADDRESS) {
                sendAddress.setTag(data.getStringExtra("id"));
                sendAddress.setText(data.getStringExtra("desc"));
            }
        }
    }

    @Override
    public void finish() {
//        noticeDialog = new PublicNoticeDialog(ApplyChangeToMeActivity.this, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (v.getId() == R.id.btn_save_notice) {
        ApplyChangeToMeActivity.super.finish();
//                }
//                noticeDialog.dismiss();
//            }
//        }, 1, "提示", "放弃编辑？",
//                "否", "是");
//        noticeDialog.show();
    }

    private void initView() {


//        mInfo = (ApplyChangerZQUserNameBean) getIntent().getSerializableExtra("mInfo");


        creditorName = (TextView) findViewById(R.id.creditor_name);
        tv_zq_phone = (TextView) findViewById(R.id.tv_zq_phone);
        tv_zq_other_phone = (TextView) findViewById(R.id.tv_zq_other_phone);
        tv_zq_id = (TextView) findViewById(R.id.tv_zq_id);

        sendAddress = (TextView) findViewById(R.id.send_address);
        edit_detail = (TextView) findViewById(R.id.edit_detail);

        tv_zq_email = (TextView) findViewById(R.id.tv_zq_email);

        if (mInfo != null) {


            if (mInfo.getChange() != null) {
                creditorName.setText(mInfo.getChange().getCreditorName());

                tv_zq_phone.setText(mInfo.getChange().getContact());
                tv_zq_other_phone.setText(mInfo.getChange().getOtherContact());
                tv_zq_id.setText(mInfo.getChange().getCardNumber());

                String addr = "";
                if (mInfo.getChange().getAddressInfo() != null) {
                    if (mInfo.getChange().getAddressInfo().getProvince() != null) {
                        addr = mInfo.getChange().getAddressInfo().getProvince();
                    }

                    if (mInfo.getChange().getAddressInfo().getCity() != null) {
                        addr += mInfo.getChange().getAddressInfo().getCity();
                    }

                    if (mInfo.getChange().getAddressInfo().getRegion() != null) {
                        addr += mInfo.getChange().getAddressInfo().getRegion();
                    }

                    if (mInfo.getChange().getAddressInfo().getAddress() != null) {
                        addr += mInfo.getChange().getAddressInfo().getAddress();
                    }

                }
                sendAddress.setText(addr);

                edit_detail.setText(mInfo.getChange().getChangeDetail());
                tv_zq_email.setText(mInfo.getChange().getEmail());

            }else{
                creditorName.setText(mInfo.getCreditorInfo().getCreditorName());

                tv_zq_phone.setText(mInfo.getCreditorInfo().getContact());
                tv_zq_other_phone.setText(mInfo.getCreditorInfo().getOtherContact());
                tv_zq_id.setText(mInfo.getCreditorInfo().getCardNumber());

                String addr = "";
                if (mInfo.getCreditorInfo().getAddressInfo() != null) {
                    if (mInfo.getCreditorInfo().getAddressInfo().getProvince() != null) {
                        addr = mInfo.getCreditorInfo().getAddressInfo().getProvince();
                    }

                    if (mInfo.getCreditorInfo().getAddressInfo().getCity() != null) {
                        addr += mInfo.getCreditorInfo().getAddressInfo().getCity();
                    }

                    if (mInfo.getCreditorInfo().getAddressInfo().getRegion() != null) {
                        addr += mInfo.getCreditorInfo().getAddressInfo().getRegion();
                    }

                    if (mInfo.getCreditorInfo().getAddressInfo().getAddress() != null) {
                        addr += mInfo.getCreditorInfo().getAddressInfo().getAddress();
                    }

                }
                sendAddress.setText(addr);

                edit_detail.setText(mInfo.getCreditorInfo().getChangeDetail());
                tv_zq_email.setText(mInfo.getCreditorInfo().getEmail());
            }
        }


    }

    /**
     * 保存信息
     */
    public void applyPerson(String status, String msg, String notifyTypes) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }

        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");

//        String no = zqUserDetailInfo.get(0).getId();
        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
//                .add("creditorId", creditorId)
                .add("auditState", status)
                .add("auditDesc", msg)
                .add("noticeTypes", notifyTypes)
                .add("projectId", mInfo.getChange().getBankruptcyProjectId())
                .add("changeId", mInfo.getChange().getId())
                .add("auditType", "6")
                .build();

        String url = Consts.WEBURL_RIGHTSAUDIT;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(ApplyChangeToMeActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
//

                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                ToastUtil.getInstance(ApplyChangeToMeActivity.this).showShortToast("审核成功");
                                finish();
//                                Toast.makeText(ApplyChangerZQUserNameActivity.this, "替吉奥成功", Toast.LENGTH_SHORT).show();

                            }

                        });
//                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ApplyChangeToMeActivity.this, "保存失败" + object.optString("msg"), Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(ApplyChangeToMeActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

}
